import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Tabs, Space, Button, Form, Row, Col, Input, message, Select, DatePicker, Checkbox, notification, Modal, Table } from 'antd';
import { connect } from 'umi';
import {
    PlusOutlined,
    CloseOutlined,
    SyncOutlined,
    ExclamationCircleOutlined,
    CheckOutlined
} from '@ant-design/icons';
import RcvDtlPo from './components/rcvDtlPo'
import * as Request from '@/services/Request';
import moment from 'moment';
import IconFont from '@/components/Iconfont';
import { EmpSelect } from '@/components/FormItemSelect';

const { TabPane } = Tabs;
const { Search } = Input;
const { confirm } = Modal;
const apiURL = "/api/services/app/RcvHead/";
const apiURLDtl = "/api/services/app/RcvDtl/";
const currentControl = "RcvHead";
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            dataSource: [],
            data: {
                data: { packSlip: '0', id: '0' },
                details: []
            },
            defTab: '1',
            pageIndex: 1,
            pageSize: 10,
            selectedRowKeys: []
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.formRef.current.setFieldsValue({ RcvHead: this.state.data });
        this.fetchDatas()
    }
    fetchDatas = () => {
        const { pageIndex, pageSize, keywords } = this.state;
        this.setState({ loading2: true })
        this.props.dispatch({
            type: 'Abp/getList',
            payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords },
            control: currentControl
        }).then(() => {
            var result = this.props.response.result;
            if (result) {
                this.setState({ dataSource: result.items, totalCount: result.totalCount, loading2: false });
            }
        })
    }
    onFinish = (values: any) => {
        const { defTab } = this.state
        if (defTab === '1') {
            this.save(values.RcvHead);
        }
        else {
            this.rcvDtlPo.formRef.current.submit();
        }

    }
    resetForm = () => {
        let data = {
            data: { packSlip: '0', id: '0' },
            details: []
        }
        this.formRef.current.resetFields()
        this.formRef.current.setFieldsValue({ RcvHead: data.data });
        this.setState({ data })
    }
    save = (model: any) => {
        var act = 'Modify'
        var method = 'POST'
        if (model.id === "0") {
            act = 'New'
            model.id = undefined
        }
        Request.post(apiURL + act, model, method).then((response) => {
            if (response) {
                if (response.success) {
                    message.success('保存成功！');
                    var RcvHead = response.result.data;
                    if (RcvHead.receiptDate)
                        RcvHead.receiptDate = moment(RcvHead.receiptDate);
                    if (RcvHead.entryDate)
                        RcvHead.entryDate = moment(RcvHead.entryDate);
                    this.formRef.current.setFieldsValue({ RcvHead });
                    this.setState({ data: { data: RcvHead } });
                    this.fetchDatas()
                }
                else {
                    notification.error({
                        message: response.error.message,
                        description: response.error.details,
                    });
                }
                this.setState({ loading: false });
            }
        });
    }
    tabSwitch = (key: any) => {
        this.setState({ defTab: key });
    }
    getObj = (value: any) => {
        if (!value) {
            return;
        }
        this.setState({ loading: true })
        Request.get(apiURL + "GetByNum?num=" + value).then((response) => {
            if (response) {
                if (response.success) {
                    var result = response.result;
                    var RcvHead = result.data;
                    if (RcvHead) {
                        if (RcvHead.receiptDate)
                            RcvHead.receiptDate = moment(RcvHead.receiptDate);
                        if (RcvHead.entryDate)
                            RcvHead.entryDate = moment(RcvHead.entryDate);
                        this.formRef.current.setFieldsValue({ RcvHead });
                        this.setState({ data: result, visible: false, loading: false })
                    }
                }
                else {
                    notification.error({
                        message: response.error.message,
                        description: response.error.details,
                    });
                }
                this.setState({ loading: false });
            }
        });
    }
    delObj = () => {
        const { data } = this.state;
        if (data.data) {
            let _this = this
            confirm({
                title: '警告',
                icon: <ExclamationCircleOutlined />,
                content: '删除后将不可恢复，确定删除？',
                onOk() {
                    _this.props.dispatch({
                        type: 'Abp/delete',
                        payload: { id: data.data.id },
                        control: currentControl
                    }).then(() => {
                        _this.fetchDatas()
                        _this.resetForm()
                    })
                },
            });
        }
    }
    switchModal = (visible: boolean, record: any = null) => {
        const { data } = this.state;
        if (record == null) {
            record = {
                packSlip: data.data.packSlip,
                receiptType: data.data.receiptType
            }
        }
        this.setState({ visible, record });
    }
    rcvDtlPo: any = RcvDtlPo;
    onRef = (ref: any) => {
        this.rcvDtlPo = ref
    }
    onSearch = (value: any) => {
        var keywords = this.state.keywords;
        keywords = value;
        this.setState({ keywords }, () => {
            this.fetchDatas();
        });
    }
    delDtl = () => {
        const { selectedRowKeys, data } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delPatch',
                    payload: selectedRowKeys,
                    control: 'RcvDtl'
                }).then(() => {
                    let _data = data
                    _data.details = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0)
                    _this.setState({ data: _data })
                })
            },
        });
    }
    completeDtl = () => {
        const { selectedRowKeys, data } = this.state
        let arrs: any = []
        let lists = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) >= 0)
        lists.forEach((item: any) => {
            arrs.push({
                packSlip: item.packSlip,
                packLine: item.packLine
            })
        });
        Request.post(apiURLDtl + "Complete", arrs).then((response) => {
            if (response.success) {
                let result = response.result
                if (result.success) {
                    message.success("收货成功")
                    this.getObj(arrs[0].packSlip)
                }
                else{
                    message.error(result.message)
                }
            }
            else {
                message.error(response.error.message);
            }
        })
    }
    render() {
        const layout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
        };
        const { data, defTab, record, dataSource, pageSize, totalCount, loading, loading2, selectedRowKeys } = this.state
        const columns = [
            {
                title: '收货单号',
                dataIndex: 'packSlip',
            },
            {
                title: '项目',
                dataIndex: 'packLine',
            },
            {
                title: '物料编码',
                dataIndex: 'partNum',
            },
            {
                title: '物料描述',
                dataIndex: 'partDescription',
            },
            {
                title: '数量',
                dataIndex: 'ourQty',
            },
            {
                title: '单位',
                dataIndex: 'ium',
            },
            {
                title: '完成',
                dataIndex: 'receivedComplete',
                key: 'receivedComplete',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
        ]
        const columns2 = [
            {
                width: 30,
                render: () => <IconFont type="icon-database" />
            },
            {
                title: '收货单号',
                dataIndex: 'packSlip',
            },
            {
                title: '收货日期',
                dataIndex: 'receiptDate',
                render: (text: string) => (
                    <span>{moment(text).format('YYYY-MM-DD')}</span>
                )
            },
            {
                title: '采购类型',
                dataIndex: 'receiptType',
            },
            {
                title: '完成',
                dataIndex: 'received',
                key: 'received',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
        ]
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys: any) => {
                this.setState({ selectedRowKeys });
            },
        };
        return (
            <PageHeaderWrapper title={false}>
                <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                    <Card title="收货入库" extra={<Space>
                        <Button key="1" type="primary" icon={<PlusOutlined />} onClick={this.resetForm}>新建</Button>
                        <Button key="2" type="primary" htmlType="submit">保存</Button>
                        <Button key="4" type="dashed" danger icon={<CloseOutlined />} onClick={this.delObj} disabled={data.data.id === "0"}>删除</Button>
                    </Space>}>
                        <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                            <TabPane tab="汇总" key="1">
                                <Row>
                                    <Col span={12}>
                                        <Form.Item name={['RcvHead', 'id']} hidden={true}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item name={['RcvHead', 'packSlip']} label="收货单号"
                                            rules={[{ required: true, message: "收货单号必填" }]}>
                                            <Input style={{ width: 200 }} onBlur={(e: any) => this.getObj(e.target.value)} disabled />
                                        </Form.Item>
                                        <Form.Item name={['RcvHead', 'receiptDate']} label="收货日期"
                                            rules={[{ required: true }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <Form.Item name={['RcvHead', 'entryDate']} label="输入日期">
                                            <DatePicker />
                                        </Form.Item>
                                        <EmpSelect showSearch width={200} name={['RcvHead', 'receivePerson']} label="收货人" />
                                        <Form.Item name={['RcvHead', 'receiptType']} label="收货类型"
                                            rules={[{ required: true, message: "收货类型必填" }]}>
                                            <Select
                                                style={{ width: 200 }}
                                                placeholder="请选择收货类型">
                                                <Select.Option value="MTL">采购收货</Select.Option>
                                                <Select.Option value="JOB">工单收货</Select.Option>
                                                <Select.Option value="UKN">其它收货</Select.Option>
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item name={['RcvHead', 'receiptComment']} label="收货备注">
                                            <Input.TextArea />
                                        </Form.Item>
                                        <Form.Item wrapperCol={{ offset: 5 }}>
                                            <Input.Group compact>
                                                <Form.Item
                                                    name={['RcvHead', 'received']}
                                                    valuePropName="checked">
                                                    <Checkbox disabled>完成收货</Checkbox>
                                                </Form.Item>
                                                <Form.Item
                                                    name={['RcvHead', 'invoiced']}
                                                    valuePropName="checked">
                                                    <Checkbox disabled>已开票</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>

                                    </Col>
                                </Row>

                            </TabPane>
                            <TabPane tab="收货明细" key="2">
                                <Table
                                    rowKey="id"
                                    size="small"
                                    columns={columns}
                                    loading={loading}
                                    dataSource={data.details}
                                    rowSelection={rowSelection}
                                    onRow={record => {
                                        return {
                                            onDoubleClick: event => { this.switchModal(true, record) },
                                        };
                                    }}
                                    footer={() =>
                                        <Space>
                                            <Button
                                                type="dashed"
                                                icon={<PlusOutlined />}
                                                onClick={() => this.switchModal(true)}>新建明细</Button>
                                            <Button
                                                type="default"
                                                icon={<CheckOutlined />}
                                                onClick={this.completeDtl}
                                                disabled={selectedRowKeys.length <= 0}>全部收货</Button>
                                            <Button
                                                type="dashed"
                                                danger
                                                icon={<CloseOutlined />}
                                                onClick={this.delDtl}
                                                disabled={selectedRowKeys.length <= 0}>删除选中</Button>
                                        </Space>
                                    }
                                />


                            </TabPane>
                        </Tabs>

                    </Card>
                </Form>
                <Card title="所有收货" extra={
                    <Space style={{ marginBottom: 16 }}>
                        <Button type="ghost"
                            onClick={() => this.fetchDatas()}
                            loading={loading2}
                            icon={<SyncOutlined />} ></Button>
                        <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                    </Space>
                }>
                    <Table
                        rowKey="id"
                        size="small"
                        columns={columns2}
                        loading={loading2}
                        dataSource={dataSource}
                        pagination={{
                            onChange: page => {
                                this.setState({ pageIndex: page }, () => {
                                    this.fetchDatas();
                                });
                            },
                            pageSize,
                            total: totalCount,
                        }}
                        onRow={record => {
                            return {
                                onDoubleClick: event => { this.getObj(record.packSlip) },
                            };
                        }}
                    /></Card>
                <Modal
                    title="收货明细"
                    visible={this.state.visible}
                    destroyOnClose={true}
                    onCancel={() => this.switchModal(false)}
                    footer={false}
                >
                    <RcvDtlPo onRef={this.onRef} data={record} refreshData={this.getObj} />
                </Modal>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);